package com.example.backend.controller;

import com.example.backend.mapper.OrderItemMapper;
import com.example.backend.mapper.OrderMapper;
import com.example.backend.model.Order;
import com.example.backend.model.OrderItem;
import com.example.backend.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;

    @GetMapping
    public Response<List<Order>> findMatchOrder(@RequestParam("userid") Integer userid) {
        List<Order> orders = orderMapper.findMatch(userid);
        orders.forEach(order -> {
            List<OrderItem> items = orderItemMapper.findMatch(order.getId());
            order.setItems(items);
        });

        return Response.Ok("all the order of this user", orders);
    }

    @PostMapping
    public Response<Integer> insertOne(@RequestBody Order order) {
        int result1 = orderMapper.insertOne(order);
        int latestid = orderMapper.findLatestId();
        order.getItems().forEach(item -> item.setOrderid(latestid));
        int result2 = orderItemMapper.insertAll(order.getItems());

        return result1 != -1 && result2 != -1 ?
                Response.Ok("insert success", result1)
                : Response.Error("insert failed", result1);
    }

    @DeleteMapping
    public Response<Integer> deleteOne(@RequestParam("id") Integer orderid) {
        Order order = orderMapper.findOne(orderid);
        List<OrderItem> items = orderItemMapper.findMatch(order.getId());

        int result1 = orderMapper.deleteOne(orderid);
        int result2 = orderItemMapper.deleteAll(items.stream().map(item -> item.getId()).collect(Collectors.toList()));

        return result1 != -1 && result2 != -1 ?
                Response.Ok("delete success", result1)
                : Response.Error("delete failed", result2);
    }

    @PutMapping
    public Response<Integer> updateOne(@RequestBody Order order) {
        int result = orderMapper.updateOne(order);
        return result != -1 ?
                Response.Ok("update success", result)
                : Response.Error("update failed", result);
    }
}
